<template>
  <div class="kefu_list">
    <el-row><el-button @click="handleAddKF">添加客服</el-button></el-row>
    <el-table v-loading="tbLoading" element-loading-text="拼命加载中" :data="kefuList" stripe class="table">
      <el-table-column prop="kf_nick" label="客服信息" className="is-center">
      </el-table-column>
      <el-table-column prop="kf_account" label="客服账号"></el-table-column>
      <el-table-column prop="kf_wx" label="绑定微信号"></el-table-column>
      <el-table-column label="操作" className="is-center">
        <template slot-scope="scope">
          <el-button v-if="scope.row.bind" type="text" @click="handleEditClick(scope.row)">编辑</el-button>
          <el-button v-else type="text" @click="handleBindClick(scope.row.kf_account)">绑定</el-button>
          <el-button type="text" @click="handleDel(scope.row.kf_account)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加客服弹层 -->
    <el-dialog :title="dialogTitle" :visible.sync="showDialog1" class="dialog_add" @open="form2.wxAccount=''">
      <el-form ref="form1" v-if="dialogStep==1" label-width="80px" :model="form1" :rules="rules">
        <el-form-item prop="nickname" label="客服名称" required>
          <el-input v-model="form1.nickname" placeholder="必填,最长16个字" :maxlength="16"></el-input>
        </el-form-item>
        <el-form-item prop="account" label="客服账号" required>
          <el-input v-model="form1.account" :disabled="dialogStatus === 'edit'" :maxlength="10" placeholder="最长10个字符，必须是英文、数字字符或者下划线"></el-input>
        </el-form-item>
        <el-form-item prop="avatarUrl" label="客服头像">
          <el-upload
            ref="upload"
            :data="datas"
            :headers="headers"
            :auto-upload="false"
            :show-file-list="false"
            :action="baseUrl + '/content/weixin/kf/account/avatar'"
            :on-change="handlePreview"
          >
            <img v-if="form1.avatarUrl" :src="form1.avatarUrl" class="avatar">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过1Mb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <el-form ref="form2" v-if="dialogStep==2" label-width="80px" :model="form2" :rules="rules">
        <el-form-item prop="wxAccount" label="微信号">
          <el-input v-model="form2.wxAccount"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button v-if="dialogStep==1" type="primary" @click="handleSaveAccount" :loading="isSave">{{dialogStatus=='new'?'下一步':'保存'}}</el-button>
        <el-button v-if="dialogStep==2" type="primary" @click="handleBindAccount" :loading="isSave">绑定</el-button>
        <el-button @click="showDialog1=false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {mapState, mapActions} from 'vuex'
  import config from '@/config/env'
  export default {
    data () {
      return {
        appid: this.$route.params.appid,
        form1: {
          account: null,
          nickname: null,
          avatarUrl: null
        },
        form2: {
          wxAccount: ''
        },
        baseUrl: config.baseUrl,
        dialogStatus: 'new',
        dialogStep: 1,
        showDialog1: false,
        isSave: false,
        tbLoading: false,
        rules: {
          wxAccount: {required: true, message: '请输入微信号', trigger: 'blur'},
          nickname: {required: true, message: '请输入昵称', trigger: 'blur'},
          account: [{required: true, message: '请输入客服账号', trigger: 'blur'},
                    {pattern: /[a-zA-Z0-9_]+/, message: '账号不符合规则', trigger: 'blur'}]
        }
      }
    },
    mounted () {
      this.initPage()
    },
    computed: {
      ...mapState({
        wechatDetail: state => state.wechatManage.wechatDetail,
        kefuList: state => state.wechatManage.kefuList
      }),
      // 文件上传头部
      headers () {
        return {
          UBToken: localStorage.getItem('UBToken')
        }
      },
      // 文件上传参数
      datas () {
        return {
          appid: this.appid, kf_account: this.account + '@' + this.wechatDetail.alias
        }
      },
      dialogTitle () {
        let title = this.dialogStep === 1 ? '新建客服' : '绑定个人微信'
        title = this.dialogStatus === 'edit' ? '编辑客服' : '新建客服'
        return title
      }
    },
    methods: {
      ...mapActions(['addKefuAccount', 'getWechatInfo', 'getKefuList', 'delKefuAccount', 'setKefuInfo', 'bindKefuAccount']),
      initPage () {
        const appid = this.appid
        this.getKefuList(appid)
        this.getWechatInfo(appid)
      },
      handlePreview (file) {
        if (this.uploadCheck(file.raw)) {
          this.form1.avatarUrl = URL.createObjectURL(file.raw)
        }
      },
      // 上传检验
      uploadCheck (file) {
        const allowTypes = ['image/jpg', 'image/jpeg', 'image/png']
        if (allowTypes.indexOf(file.type) === -1) {
          this.$message.warning('图片格式不支持')
          this.$refs.upload.clearFiles()
          return false
        } else if (file.size / 1024 > 1024) {
          this.$message.warning('图片大小不合法')
          this.$refs.upload.clearFiles()
          return false
        }
        return true
      },
      handleAddKF () {
        this.dialogStep = 1
        this.dialogStatus = 'new'
        this.form1.account = this.form1.nickname = this.form1.avatarUrl = null
        this.showDialog1 = true
      },
      // 删除客服
      async handleDel (account) {
        await this.$confirm('是否确认删除？', '确认')
        const res = await this.delKefuAccount({
          appid: this.appid,
          kf_account: account
        })
        res.data.code === 1 && this.$message.success('删除成功')
      },
      // 点击编辑客服
      handleEditClick (detail) {
        this.dialogStatus = 'edit'
        this.dialogStep = 1
        this.showDialog1 = true
        this.form1.account = detail.kf_account.split('@')[0]
        this.form1.nickname = detail.kf_nick
        this.form1.avatarUrl = detail.kf_headimgurl
      },
      // 点击绑定客服
      handleBindClick (account) {
        this.curAccount = account
        this.dialogStep = 2
        this.showDialog1 = true
      },
      // 保存客服
      async handleSaveAccount () {
        if (this.dialogStatus === 'new') { // 新增
          this.$refs.form1.validate(valid => {
            if (valid) {
              this.isSave = true
              this.addKefuAccount({
                appid: this.appid,
                kf_account: this.form1.account + '@' + this.wechatDetail.alias,
                nickname: this.form1.nickname
              }).then(res => {
                this.isSave = false
                if (res.data.code === 1) {
                  this.$refs.upload.submit()
                  this.dialogStep = 2
                  this.curAccount = this.form1.account + '@' + this.wechatDetail.alias
                  this.getKefuList(this.appid)
                }
              })
            }
          })
        } else { // 编辑
          this.$refs.form1.validate(valid => {
            if (valid) {
              this.setKefuInfo({
                appid: this.appid,
                kf_account: this.form1.account + '@' + this.wechatDetail.alias,
                nickname: this.form1.nickname
              }).then(res => {
                this.isSave = false
                if (res.data.code === 1) {
                  this.$refs.upload.submit()
                  this.$message.success('修改成功')
                  this.getKefuList(this.appid)
                  this.showDialog1 = false
                }
              })
            }
          })
        }
      },
      // 绑定客服
      async handleBindAccount () {
        this.$refs.form2.validate(valid => {
          if (valid) {
            this.isSave = true
            this.bindKefuAccount({
              appid: this.appid,
              kf_account: this.curAccount,
              invite_wx: this.form2.wxAccount
            }).then(res => {
              this.isSave = false
              if (res.data.code === 1) {
                this.$message.success('邀请绑定成功')
                this.showDialog1 = false
                this.getKefuList(this.appid)
              }
            })
          }
        })
      }
    }
  }
</script>
<style lang="scss">
  .kefu_list{
    .el-row{margin-bottom:15px}
    .dialog_add{
      .avatar{display:block;margin-bottom:15px;width:100px;height:100px;border-radius:50%;}
    }
  }
</style>
